package cn.devzyh.controller;

import cn.devzyh.domain.Course;
import cn.devzyh.domain.CourseVo;
import cn.devzyh.domain.ResultVo;
import cn.devzyh.service.CourseService;
import cn.devzyh.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 课程模块处理器
 */
@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    // 多条件查询课程列表
    @PostMapping("/findByCondition")
    public ResultVo findByCondition(@RequestBody CourseVo courseVo) {

        ResultVo res = new ResultVo(
                true,
                0,
                "响应成功",
                courseService.findByCondition(courseVo)
        );

        return res;
    }

    // 课程文件上传
    @PostMapping("/courseUpload")
    public ResultVo courseUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IOException {

        if (file.isEmpty()) {
            return new ResultVo(false, 500, "上传文件不可为空", null);
        }

        String newFileName = UploadUtil.upload(file, req);
        Map<String, String> map = new HashMap<>();
        map.put("fileName", newFileName);
        map.put("filePath", "http://127.0.0.1:8080/upload/" + newFileName);
        return new ResultVo(true, 200, "上传文件成功", map);
    }

    // 新增或修改课程和教师信息
    @PostMapping("/saveOrUpdateCourse")
    public ResultVo saveOrUpdateCourse(@RequestBody CourseVo courseVo) {

        ResultVo res = new ResultVo(true, 200, "", null);
        if (null == courseVo.getId()) {

            courseService.saveCourseAndTeacher(courseVo);
            res.setMessage("课程新增成功");
        } else {

            courseService.updateCourseAndTeacher(courseVo);
            res.setMessage("课程修改成功");
        }
        return res;
    }

    // 查询指定 ID 的课程信息
    @GetMapping("/findCourseById")
    public ResultVo saveOrUpdateCourse(@RequestParam(value = "id", required = true) Integer id) {

        Course course = courseService.findOneById(id);
        return new ResultVo(true, 200, "响应成功", course);
    }

    // 修改课程状态
    @GetMapping("/updateCourseStatus")
    public ResultVo updateCourseStatus(@RequestParam(value = "id", required = true) Integer id,
                                       @RequestParam(value = "status", required = true) Integer status) {

        courseService.updateCourseStatus(id, status);
        Map map = new HashMap();
        map.put("status", status);
        return new ResultVo(true, 200, "响应成功", map);
    }

}
